package com.example.temp.controller;

import com.example.temp.common.Result;
import com.example.temp.entity.User;
import com.example.temp.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
    // 依赖注入，运行时，IOC容器提供该类型的bean对象，并赋值给该变量
    @Autowired
    private UserMapper userMapper;

    // 查询用户
    @PostMapping("/find")
    public Result findUser(@RequestBody User user){
        User users = userMapper.find(user);
        return Result.success(users);
    }

    // 通过id查询用户（使用GET请求）
    @GetMapping("/query")
    public Result queryUser(@RequestParam String id){
        // 使用id查询用户
       User user = userMapper.query(id);
        return Result.success(user);
    }

    // 插入用户
    @PostMapping("/insert")
    public Result insertUser(@RequestBody User user){
        // 如果角色为空，默认设置为学生(2)
        if (user.getRole() == null) {
            user.setRole(2);
        }
        int user1 = userMapper.insert(user);
        return Result.success(user1);
    }

    //更新用户信息
    @PostMapping("/update")
    public Result updateUser(@RequestBody User user){
        int user1 = userMapper.update(user);
        return Result.success(user1);
    }

    // 删除用户
    @DeleteMapping("/{id}")
    public Result deleteUser(@PathVariable String id) {
        int result = userMapper.delete(id);
        if (result == 1) {
            return Result.success();
        } else {
            return Result.fail();
        }
    }
    
    // 根据角色查询用户
    @GetMapping("/role/{role}")
    public Result getUsersByRole(@PathVariable Integer role) {
        List<User> users = userMapper.findByRole(role);
        return Result.success(users);
    }
    
    // 获取所有用户
    @GetMapping("/all")
    public Result getAllUsers() {
        List<User> users = userMapper.findAll();
        return Result.success(users);
    }
}
